package com.test.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.test.ssm.pojo.Bill;
import com.test.ssm.service.BillService;
import com.test.ssm.service.ProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 徒有琴
 */
@Controller
public class BillController {
    @Autowired
    private BillService billService;

    @Autowired
    private ProviderService providerService;

    @RequestMapping("billList.html")
    public String list(Bill bill, Integer pageNum, Model model) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        PageInfo<Bill> pageInfo = billService.getBillList(bill, pageNum, 2);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("providers", providerService.getProName());
        return "billList";
    }

    @RequestMapping("goBillEdit.html")
    public String goEdit(Integer id, Model model) {
        model.addAttribute("providers", providerService.getProName());
        if (id != null) {
            Bill bill = billService.getBillById(id);
            model.addAttribute("bill", bill);
        }
        return "billEdit";
    }

    @RequestMapping("doEditBill.html")
    public String edit(Bill bill, Model model) {
        try {
            if (bill.getId() == null) {
                billService.insert(bill);
            } else {
                billService.update(bill);
            }
            return "redirect:billList.html";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("message", "编辑失败");
            return "forward:goBillEdit.html";
        }
    }

    @RequestMapping("delBill.html")
    public String del(Integer id){
        billService.deleteById(id);
        return "redirect:billList.html";
    }
}
